const ArticleModel = require('../models/index').getModel('article')
const mongoose = require('mongoose')
const USER_REF = {
    '$lookup': {
        'from': 'user',
        'localField': 'author',
        'foreignField': '_id',
        'as': 'user'
    }
}

function articleModelKeyTypeFilter(article) {
    if (article.published !== undefined && article.published !== null) {
        article.published = parseInt(article.published, 10)
    }

    if (article.visiblePermission !== undefined && article.visiblePermission !== null) {
        article.visiblePermission = parseInt(article.visiblePermission, 10)
    }

    if (article.replyPermission !== undefined && article.replyPermission !== null) {
        article.replyPermission = parseInt(article.replyPermission, 10)
    }

    if (article.viewNum !== undefined && article.viewNum !== null) {
        article.viewNum = parseInt(article.viewNum, 10)
    }

    if (article.top !== undefined && article.top !== null) {
        article.top = parseInt(article.top, 10)
    }
}

const articleService = {
    // 获取文章数量
    async getArticleCount(query) {
        articleModelKeyTypeFilter(query)
        return ArticleModel.where(query).countDocuments()
    },

    // 获取置顶文章
    async getTopArticle() {
        return ArticleModel.aggregate([
            {$match: {top: 1}},
            {$sort: {topIndex: 1}},
            {
                $project: {
                    title: 1,
                    author: 1,
                    createTime: 1,
                    updateTime: 1,
                    viewNum: 1,
                    description: 1,
                    cover: 1,
                    visiblePermission: 1,
                    replyPermission: 1,
                    published: 1,
                    category: 1,
                    tag: 1,
                    likes: 1,
                    // 1顶
                    top: 1,
                    // 1重
                    topIndex: 1,
                    commentCount: {
                        $cond: {
                            if: {$isArray: "$comments"},
                            then: {$size: "$comments"},
                            else: "NA"
                        }
                    }
                }
            },
            USER_REF
        ])
    },

    // 获取文章
    async getArticle(query = {},
                     sort = {createTime: -1},
                     pagination = {page: 1, limit: 12}) {
        let articleQuery = {}
        let type = 'edit'
        // 处理分页的参数和文章参数
        Object.keys(query).map(key => {
            if (key !== 'page' && key !== 'limit') {
                if (key === 'type') {
                    type = query[key]
                } else if (key !== 'sort' && key !== 'asc' && key !== 'key') {
                    articleQuery[key] = query[key]
                }
            } else {
                pagination[key] = query[key]
            }
        })

        // 处理排序的参数
        if (query.sort) {
            sort = {}
            // 排序参数不为数字
            sort[query.sort] = +query.asc
        }

        // 处理模糊查询
        if (query.key) {
            const pattern = /[\\\[\]\/?\s]/g;
            query.key = query.key.replace(pattern, "");
            let title = query.key.split(' ').filter(k => {
                return k !== ''
            })
            articleQuery.title = {$regex: title.join('|')}
        }

        // 处理参数为字符串的问题
        articleModelKeyTypeFilter(articleQuery)
        // 查询具体文章的时候需要返回评论和内容
        if (articleQuery._id) {
            articleQuery._id = new mongoose.Types.ObjectId(articleQuery._id)
            if (type === 'read') {
                await ArticleModel.findByIdAndUpdate(articleQuery._id, {$inc: {viewNum: 1}}, {new: true})
            }
            return ArticleModel.aggregate([
                {$match: articleQuery},
                USER_REF
            ])
        } else {
            return ArticleModel.aggregate(
                [
                    {$match: articleQuery},
                    {$sort: sort},
                    {$skip: (+pagination.page - 1) * pagination.limit},
                    {$limit: +pagination.limit},
                    {
                        $project: {
                            title: 1,
                            author: 1,
                            createTime: 1,
                            updateTime: 1,
                            viewNum: 1,
                            description: 1,
                            cover: 1,
                            visiblePermission: 1,
                            replyPermission: 1,
                            published: 1,
                            category: 1,
                            tag: 1,
                            likes: 1,
                            // 1顶
                            top: 1,
                            // 1重
                            topIndex: 1,
                            commentCount: {
                                $cond: {
                                    if: {$isArray: "$comments"},
                                    then: {$size: "$comments"},
                                    else: "NA"
                                }
                            }
                        }
                    },
                    USER_REF
                ]
            )
        }
    },

    // 删除文章
    async deleteArticle(articleList) {
        return ArticleModel.deleteMany(articleList)
    },

    // 创建文章
    async createArticle(articleList) {
        return ArticleModel.insertMany(articleList)
    },

    // 修改文章
    async updateOneArticle(id, update) {
        return ArticleModel.findByIdAndUpdate(id, update, {new: true})
    },

    // 更新评论
    async updateArticleComment(comment) {
        console.log(comment)
        let articleId = comment.articleId
        comment = comment.comment
        let level = comment.level
        if (level === 0) {
            return ArticleModel.findByIdAndUpdate(articleId, {
                $push: {
                    comments: {
                        $each: [comment],
                        $position: 0
                    }
                }
            })
        } else {
            let match = 'comments'
            let arrayFilters = []
            for (let i = 0; i < level; i++) {
                let filterPart = {}
                let matchPart = `.$[${'index' + i}].comments`
                match += matchPart
                filterPart['index' + i + '.id'] = comment.parent[i]
                arrayFilters.push(filterPart)
            }
            let query = {}
            let options = {arrayFilters}
            query[match] = {
                $each: [comment],
                $position: 0
            }
            // console.log('------------------updateArticleComment------------------------')
            // console.log(query)
            // console.log(options)
            // console.log('------------------updateArticleComment------------------------')
            return ArticleModel.findByIdAndUpdate(articleId, {$push: query}, options)
        }
    },

    // 选择更新文章 不返回更新后的文章数据
    async updateArticle(id, update) {
        return ArticleModel.updateOne(id, update)
    },

    // 处理每个分类下文章的数量 每天更新一次
    async getArticleCountUnderCategory() {
        return ArticleModel.aggregate(
            [
                {$unwind: "$category"},
                {$group: {_id: "$category", articleCount: {$sum: 1}}}
            ]
        )
    },

    // 获取热门的文章 按什么排序呢？ 点击量吧？
    async getHotArticle(limit = 6) {
        // await this.updateHttps()
        return ArticleModel.aggregate(
            [
                {$sort: {viewNum: -1}},
                {$skip: 0},
                {$limit: +limit},
                {
                    $project: {
                        title: 1,
                        author: 1,
                        createTime: 1,
                        viewNum: 1,
                        cover: 1,
                        commentCount: {
                            $cond: {
                                if: {$isArray: "$comments"},
                                then: {$size: "$comments"},
                                else: "NA"
                            }
                        }
                    }
                },
                USER_REF,
            ]
        )
        // return ArticleModel.find({}, {
        //     cover: 1,
        //     viewNum: 1,
        //     title: 1,
        //     author: 1,
        //     createTime: 1,
        // }).sort({ viewNum: -1 }).skip(0).limit(+limit)
    },

    async updateHttps() {
        // let result = await ArticleModel.find({'cover': {'$regex': /daisy-api.icu/}})
        // result.map(async (item) => {
        //         var tmp = String(item.cover)
        //         tmp = tmp.replace('daisy-api.icu', 'daisyz.cn')
        //         console.log('updateHttps', tmp)
        //         let r = await ArticleModel.findByIdAndUpdate(item._id, {$set: {cover: tmp}}, {new: true});
        //         console.log('------------', r)
        //     }
        // );

        let result1 = await ArticleModel.find({'content': {'$regex': /daisy-api.icu/}})
        console.log('------------------------', result1)
        result1.map(async (item) => {
                var tmp = String(item.content)
                tmp = tmp.replace('daisy-api.icu', 'daisyz.cn')
                console.log(1233333333333333, tmp)
                console.log(await ArticleModel.findByIdAndUpdate(item._id, {$set: {content: tmp}}))
            }
        )
    }
}

module.exports = articleService
